package com.peng.leetcode.tree;

/**
 * DeleteNode2
 * <p>
 * Created on 2022/12/8
 *
 * @author lupeng
 */
public class DeleteNode2 {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val == key) {
            if (root.left == null && root.right == null) {
                return null;
            }
            if (root.left == null) {
                return root.right;
            }
            if (root.right == null) {
                return root.left;
            }
            TreeNode curr = root.right;
            while (curr.left != null) {
                curr = curr.left;
            }
            root.right = deleteNode(root.right, curr.val);
            curr.left = root.left;
            curr.right = root.right;
            return curr;
        } else if (root.val > key) {
            root.left = deleteNode(root.left, key);
        } else {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }
}
